package org.example.fastproject.core.security;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import org.example.fastproject.core.bean.ViewResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 王海舟
 * @Date 2023/1/18 12:25
 * @PackageName:org.example.fastproject.core.security
 * @ClassName: AccessDeniedHandler
 * @Description: 访问拒绝处理类
 * @Version 1.0
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        //设置响应格式
        response.setStatus(HttpStatus.HTTP_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //生成json数据
        ViewResult viewResult = ViewResult.error(HttpStatus.HTTP_FORBIDDEN,"访问被拒绝");
        String json = JSONUtil.toJsonStr(viewResult);
        //返回数据
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.close();
    }
}
